import java.io.*;
import java.nio.charset.Charset;

/**
 * @author 支绍昆
 * 2024/2/29
 * 调用系统命令
 **/
public class ProcessBuilderDemo {

    public static void main(String[] args) {
        System.out.println("start");
        //windows
        exec("D:", "cmd", "/c", "dir");
        exec("D:\\apache-seatunnel-2.3.4","cmd","/c",".\\bin\\seatunnel.cmd","--config",".\\config\\v2.batch.config.template","-e","local");
        //linux
        exec("/usr","ls");
    }

    public static void exec(String curDir, String... command) {
        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(new File(curDir));
        pb.command(command);
        pb.redirectErrorStream(true);
        Process process = null;
        try {
            process = pb.start();
            try (InputStream in = process.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("GBK")));) {
                String line;
                while (null != (line = reader.readLine())) {
                    System.out.println(line);
                }
            }
            if (0 == process.waitFor()) {
                System.out.println("run success.");
            } else {
                System.out.println("run fail!");
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != process) process.destroy();
        }
    }

}
